<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col
        class="aaa"
        :span="show ? rowObj.T1 : rowObj.F1"
        :xs="show ? rowObj.T2 : rowObj.F2"
      >
        <workSiteLeft
          ref="workSiteLeft"
          :show="show"
          @showLeft="showLeft"
          @queryVal="queryVal"
        />
      </el-col>
      <el-col
        :span="show ? rowObj.T3 : rowObj.F3"
        :xs="show ? rowObj.T4 : rowObj.F4"
      >
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="mini"
          :inline="true"
          label-width="70px"
        >
          <el-button
            style="margin-right: 6px"
            size="mini"
            :icon="show ? 'el-icon-s-fold' : 'el-icon-s-unfold'"
            circle
            @click="showLeft(show)"
          ></el-button>
          <!-- <el-form-item label="拌合楼" prop="stationCode">
            <el-select
              style="width: 160px"
              v-model="queryParams.stationCode"
              clearable
              size="mini"
              placeholder="请选择拌合楼"
            >
              <el-option
                v-for="item in cementListData"
                :key="item.id"
                :label="item.name"
                :value="item.code"
              >
              </el-option>
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item label="配方编号" prop="matchCode">
            <el-select
              style="width: 160px"
              v-model="queryParams.matchCode"
              clearable
              size="mini"
              placeholder="请选择配方编号"
              @change="matchCodeChange"
            >
              <el-option
                v-for="item in quListData"
                :key="item.id"
                :label="item.matchCode"
                :value="item.matchCode"
              >
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="选择时间">
            <el-select
              filterable
              v-model="timeType"
              style="width: 100px; margin-right: 8px"
              :popper-append-to-body="false"
              @change="handleTimeType"
            >
              <el-option label="投产以来" value="all"></el-option>
              <el-option label="按年" value="year"></el-option>
              <el-option label="自定义" value="other"></el-option>
            </el-select>
            <deatetime
              v-if="'other' == timeType"
              ref="deatetime"
              v-model="queryParams.timeRange"
            >
            </deatetime>
            <el-date-picker
              style="width: 120px"
              v-if="'year' == timeType"
              v-model="queryParams.year"
              value-format="yyyy"
              format="yyyy"
              type="year"
              placeholder="选择年"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button type="success" icon="el-icon-thumb" size="mini"
                       :loading="checkLoading" @click="handleCheck">手动校验</el-button>
            <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        > -->
          </el-form-item>
        </el-form>
        <div v-loading="loading">
          <!-- <div class="chartBox">
            <div id="myChar" style="`width: 100%;height: 100%;transform-origin: 0 0;`"></div>
          </div> -->
          <!-- style="margin-top: -15px" -->
          <el-table
            border
            size="mini"
            :data="cementDataList"
            show-overflow-tooltip="true"
            highlight-current-row
            stripe
            :span-method="setTableMethod"
            :height="tableHeight"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" fixed />
            <el-table-column
              label="拌合站名称"
              align="center"
              width="150"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <span>{{ scope.row.stationName || "-" }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column label="配比编号" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.matchCode || "-" }}</span>
              </template>
            </el-table-column> -->
            <el-table-column
              label="出料时间"
              width="160px"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <span>{{ scope.row.occurTime || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="批次总量"
              min-width="110px"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <span>{{ scope.row.batchWeight || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="类别"
              width="100px"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <span>{{ scope.row.desc || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column
              v-if="colControl.gravel1.show"
              key="sjgl1"
              label="骨料1"
              align="center"
              min-width="120"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.sjgl1 || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column
              v-if="colControl.gravel2.show"
              prop="sjgl2"
              key="sjgl2"
              :label="colControl.gravel2.name"
              align="center"
              min-width="120"
            ></el-table-column>
            <el-table-column
              v-if="colControl.gravel3.show"
              prop="sjgl3"
              key="sjgl3"
              :label="colControl.gravel3.name"
              align="center"
              min-width="120"
            ></el-table-column>
            <el-table-column
              v-if="colControl.gravel4.show"
              prop="sjgl4"
              key="sjgl4"
              :label="colControl.gravel4.name"
              align="center"
              min-width="120"
            ></el-table-column>
            <el-table-column
              v-if="colControl.gravel5.show"
              prop="sjgl5"
              key="sjgl5"
              :label="colControl.gravel5.name"
              align="center"
              min-width="120"
            ></el-table-column>
            <el-table-column
              v-if="colControl.gravel6.show"
              prop="sjgl6"
              key="sjgl6"
              :label="colControl.gravel6.name"
              align="center"
              min-width="120"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.sjgl6 || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column
              v-if="colControl.powder1.show"
              prop="sjfl1"
              key="sjfl1"
              :label="colControl.powder1.name"
              align="center"
              min-width="120"
            ></el-table-column>
            <el-table-column
              v-if="colControl.powder2.show"
              prop="sjfl2"
              key="sjfl2"
              :label="colControl.powder2.name"
              align="center"
              min-width="120"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.sjfl2 || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column
              v-if="colControl.water.show"
              prop="actualWater"
              key="actualWater"
              :label="colControl.water.name"
              align="center"
              min-width="120"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.actualWater || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="水胶比"
              min-width="120px"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <span>{{ scope.row.sjbR || "-" }}</span>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import constant from "@/api/waterStability/producedData/constant";
import workSiteLeft from "@/views/components/workSiteLeft";
import {
  cementList,
  quList,
  getLastYear,
  cementDataList,
  handCheck,
} from "@/api/waterStability/producedData/monitor";

import deatetime from "@/components/Datetime";

export default {
  name: "monitor", //生产数据监控
  data() {
    return {
      show: true,
      rowObj: {
        T1: 3,
        T2: 24,
        T3: 21,
        T4: 24,
        F1: 0,
        F2: 0,
        F3: 24,
        F4: 24,
      },
      myChar: null,
      chartWidth: 0,
      chartHeight: 0,
      currentMatch: null,
      // 控制显示隐藏表格列
      colControl: {
        gravel1: { show: true, name: "骨料1" },
        gravel2: { show: true, name: "骨料2" },
        gravel3: { show: true, name: "骨料3" },
        gravel4: { show: true, name: "骨料4" },
        gravel5: { show: true, name: "骨料5" },
        gravel6: { show: true, name: "骨料6" },
        powder1: { show: true, name: "粉料1" },
        powder2: { show: true, name: "粉料2" },
        water: { show: true, name: "水" },
      },
      // 默认表格列名称
      colNameDef: {
        gravel1: "骨料1",
        gravel2: "骨料2",
        gravel3: "骨料3",
        gravel4: "骨料4",
        gravel5: "骨料5",
        gravel6: "骨料6",
        powder1: "粉料1",
        powder2: "粉料2",
        water: "水",
      },
      forceCurve: false,
      timeType: "all",
      cementListData: [],
      quListData: [],
      lastYear: "",

      totalTwo: 0,
      loadingTwo: false,
      constructionList: [], //工地列表
      rowDetailsDialog: false,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      checkLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 水稳拌合站数据表格数据
      cementDataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stationCode: undefined,
        matchCode: undefined,
        year: undefined,
        timeRange: [undefined, undefined],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [{ required: true, message: "数据主键不能为空", trigger: "blur" }],
        baseCode: [
          { required: true, message: "机构code不能为空", trigger: "blur" },
        ],
      },
      tableHeight: window.innerHeight - 230
    };
  },
  components: {
    deatetime,
    workSiteLeft,
  },
  created() {
    this.getCementList();
    this.getQuList();
    // this.getLastYearApi();
  },
  methods: {
    // 合并单元格
    setTableMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 3 ) {
        if (rowIndex % 3) {
          return [1, 0];
        } else {
          return [3, 1];
        }
      }
    },
    showLeft(show) {
      this.show = !show;
    },
    queryVal(val) {
      this.queryParams.id = val.id;
      this.handleQuery();
    },
    // 查询拌合楼下拉列表
    getCementList() {
      cementList().then((res) => {
        this.cementListData = res.data || [];
      });
    },
    // 查询配方编号下拉
    getQuList() {
      quList().then((res) => {
        this.quListData = res.data || [];
        this.getList();
      });
    },
    // 查询时间
    getLastYearApi() {
      getLastYear().then((res) => {
        if (!!res.data) {
          this.timeType = "year";
          this.lastYear = res.data[0];
          this.queryParams["year"] = res.data[0];
          this.getList();
        }
      });
    },
    /** 查询水稳拌合站数据列表 */
    getList() {
      this.loading = true;
      cementDataList(this.queryParams).then((response) => {
        this.cementDataList = response.data.records;
        // 根据选中的配方设置表格列显示隐藏
        this.total = response.data.total;
        // this.createChar();
        this.loading = false;
      });
    },

    handleTimeType(val) {
      if (val == "year") {
        this.queryParams["year"] = this.lastYear;
      }
    },
    /**
     * 配方数据变化
     */
    matchCodeChange(val) {
      if (val) {
        this.currentMatch = val;
      } else {
        this.currentMatch = null;
      }
    },
    /**
     * 设置表格控制
     */
    initColControl() {
      console.log(this.currentMatch);
      if (this.currentMatch == null || undefined == this.currentMatch) {
        for (const key in this.colControl) {
          this.colControl[key].show = true;
          this.colControl[key].name = this.colNameDef[key];
        }
      } else {
        let colName;
        for (const key in this.colControl) {
          this.colControl[key].show = !!this.currentMatch[key];
          colName = this.currentMatch[key + "Name"];
          this.colControl[key].name = !!colName
            ? colName
            : this.colNameDef[key];
        }
      }
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams = this.getSearchParams();
      this.queryParams.pageNum = 1;
      this.getList();
    },
    getSearchParams() {
      // 根据选中的配方设置表格列显示隐藏
      this.initColControl();
      // 拼接查询条件
      let params = {};
      for (let key in this.queryParams) {
        if ("year" != key && "timeRange" != key) {
          params[key] = this.queryParams[key];
        }
      }

      if ("year" == this.timeType && !!this.queryParams["year"]) {
        params["year"] = this.queryParams["year"];
      } else if ("other" == this.timeType && !!this.queryParams["timeRange"]) {
        params["startDate"] = this.queryParams["timeRange"][0];
        params["endDate"] = this.queryParams["timeRange"][1];
      }

      return params;
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.$refs.deatetime.startTime = null;
      // this.$refs.deatetime.endTime = null;
      // this.queryParams.time = [];
      // this.queryParams.startTime = "";
      // this.queryParams.endTime = "";
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /**
     * 创建图表
     */
    createChar() {
      if (null == this.myChar) {
        this.myChar = echarts.init(document.getElementById("myChar"));
      } else {
        this.myChar.clear();
      }
      this.myChar.showLoading({
        text: "暂无数据",
        color: "#ffffff",
        textColor: "#8a8e91",
        maskColor: "rgba(255, 255, 255, 0.8)",
      });

      const lData = [];
      const sData = [];
      const colorArray = [];
      const xData = [];
      if (!!this.cementDataList) {
        let item;
        for (let i = this.cementDataList.length - 1; i >= 0; i--) {
          item = this.cementDataList[i];
          xData.push(item.dischargeTime);
        }

        let data;
        for (var key in this.colControl) {
          lData.push(this.colControl[key].name);
          colorArray.push(constant.colors[key + "Act"]);
          data = [];
          for (let i = this.cementDataList.length - 1; i >= 0; i--) {
            item = this.cementDataList[i];
            data.push(item[key + "Act"]);
          }
          sData.push({
            name: this.colControl[key].name,
            type: "bar",
            barGap: 0,
            barMaxWidth: 40,
            data: data,
            stack: "equal",
          });
        }
      }

      this.myChar.setOption({
        color: colorArray,
        legend: {
          data: lData,
          left: "center",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        xAxis: {
          data: xData,
          axisLine: { onZero: true },
          splitLine: { show: false },
          splitArea: { show: false },
        },
        yAxis: {
          name: "单位(吨)",
        },
        grid: {
          top: 40,
          bottom: 60,
          left: 40,
          right: 20,
        },
        series: sData,
      });
      this.myChar.hideLoading();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 手动校验
    handleCheck() {
      this.$confirm('正式系统禁止手动预警！', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass:'confirm-model',
        type: 'warning',
      }).then(_ => {
        this.checkLoading = true
        if (this.ids.length) {
          handCheck({ ids: this.ids }).then((res) => {
            this.checkLoading = false
            if (res.code == 200) {
              this.$message.success('手动校验成功！')
              this.resetQuery()
            } else {
              this.$message.error('手动校验失败！')
            }
          }).catch(
            (err) => {
              this.$message.error('手动校验失败！')
              this.checkLoading = false
            }
          )
        } else {
          this.checkLoading = false
          this.$message.error('请先在表格内勾选您要校验的数据！')
        }
      })
    },
  },
};
</script>
<style scoped lang="scss">
// .app-monitor {
//   padding-top: 16px;
//   user-select: none;
// }
.chartBox {
  // width: calc(100% - 240px);
  width: 100%;
  height: 350px;
}
</style>

